/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-03-15 22:30:05
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-12-03 20:23:00
 * @FilePath: /reactTrade/src/common/request/request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { message } from 'antd';
import type { AxiosInstance, AxiosRequestConfig } from 'axios';
import axios from 'axios';
import { Loading } from 'ipeacock-ui';
import { toLogin } from './router';
import { getToken } from './utils';

/**
 * 一、功能
 * 1. 统一拦截http错误请求码
 */
export const createAxios = (config?: AxiosRequestConfig): AxiosInstance => {
  const instance = axios.create({
    timeout: 300000, //超时配置
    withCredentials: true, // 跨域携带cookie
    ...config, // 自定义配置覆盖基本配置
  });

  instance.interceptors.request.use(
    (config: any) => {
      // 在发送之前做些什么
      const { loading = true } = config;
      const jwt_token = getToken();
      if (jwt_token) {
        config.headers.Authorization = `Bearer ` + jwt_token;
      }
      if (loading) {
        Loading.show();
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  instance.interceptors.response.use(
    (response) => {
      // 对响应数据做点什么
      const { loading = true } = response.config;
      if (loading) {
        Loading.hide();
      }
      const { code, data, msg, success } = response.data;
      if (code === 200) {
        if (msg) {
          if (success) {
            message.success(msg);
          } else {
            message.error(msg);
          }
        }
        return data;
      }
    },
    (error) => {
      // 对响应错误做点什么
      Loading.hide();
      const status = error.response.status;
      // 未授权，请重新登录
      if (status === 401) {
        toLogin();
        message.error('用户未登录，请先登录');
        return Promise.reject(error);
      }
      message.error(error.response.data.message || '服务端异常');
      return Promise.reject(error);
    },
  );

  return instance;
};

export const request = createAxios({
  baseURL: '/api',
});

export const get = (url: string, params?: any) => {
  return request({
    method: 'get',
    url,
    params,
  });
};

export const post = <req, res>(url: string, data: any) => {
  return request<req, res>({
    method: 'post',
    url,
    data,
  });
};

export const put = (url: string, data?: any) => {
  return request({
    method: 'put',
    url,
    data,
  });
};

export const deleted = (url: string, params?: any) => {
  return request({
    method: 'delete',
    url,
    params,
  });
};
